import { Navigate, useNavigate } from "@solidjs/router";
import { type AnyFieldApi, createForm } from "@tanstack/solid-form";
import { Show } from "solid-js";
import { z } from "zod";
import Button from "@/components/Button";
import Input from "@/components/Input";
import Panel from "@/components/Panel";
import useAuthStore from "@/store/auth";

export default function LoginView() {
  const { auth, login } = useAuthStore();
  const navigate = useNavigate();

  const form = createForm(() => ({
    defaultValues: {
      username: "",
      password: "",
    },
    validators: {
      onChange: z.object({
        username: z.string().min(3, "用户名至少应包含3个字符。"),
        password: z.string().min(6, "密码至少应包含6个字符。"),
      }),
    },
    onSubmit: async ({ value }) => {
      const result = await login(value.username, value.password);
      if (result.ok) {
        navigate("/", { replace: true });
      } else {
        alert(result.message);
      }
    },
  }));

  return (
    <Show when={auth.status !== "ok"} fallback={<Navigate href="/" />}>
      <Panel class="w-80 mt-12 mx-auto">
        <form
          class="flex flex-col gap-4"
          onSubmit={(e) => {
            e.preventDefault();
            e.stopPropagation();
            form.handleSubmit();
          }}
        >
          <h1>登录</h1>
          <form.Field name="username">
            {(field) => (
              <>
                <label for={field().name}>用户名：</label>
                <Input
                  value={field().state.value}
                  onBlur={field().handleBlur}
                  onInput={(e) => field().handleChange(e.target.value)}
                />
                <FieldInfo field={field()} />
              </>
            )}
          </form.Field>
          <form.Field name="password">
            {(field) => (
              <>
                <label for={field().name}>密码：</label>
                <Input
                  type="password"
                  value={field().state.value}
                  onBlur={field().handleBlur}
                  onInput={(e) => field().handleChange(e.target.value)}
                />
                <FieldInfo field={field()} />
              </>
            )}
          </form.Field>
          <form.Subscribe
            selector={(state) => ({
              canSubmit: state.canSubmit,
              isSubmitting: state.isSubmitting,
            })}
          >
            {(state) => (
              <Button type="submit" disabled={!state().canSubmit}>
                {state().isSubmitting ? "..." : "登录"}
              </Button>
            )}
          </form.Subscribe>
        </form>
      </Panel>
    </Show>
  );
}

function FieldInfo(p: { field: AnyFieldApi }) {
  return (
    <>
      {p.field.state.meta.isTouched && p.field.state.meta.errors.length ? (
        <em>{p.field.state.meta.errors[0].message}</em>
      ) : null}
      {p.field.state.meta.isValidating ? "Validating..." : null}
    </>
  );
}
